// import 'package:dim/dim.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:dim/dim.dart';
import 'package:flutter/material.dart';
// import 'package:sharesdk/sharesdk.dart';
// import 'package:sharesdk/sharesdk_register.dart';
import 'package:wanchong/conf.dart';
import 'package:wanchong/path.dart';
import 'package:wanchong/router.dart';
import 'package:flutter/services.dart';
import 'package:wanchong/utils/common.dart';
import 'package:wanchong/utils/event_bus.dart';

// class App extends StatelessWidget {

// }
///全局搜索历史，在app启动的时候加载
List<String> history = List();

///聊天句柄
Dim dim = new Dim();
String self = "";
ImUser imUserSelf;

class App extends StatefulWidget {
  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<App> {
  StreamSubscription<dynamic> _messageStreamSubscription;
  // Dim _dim = new Dim();
  // int appid = 1400215656;
  String _result = "";
  @override
  void initState() {
    super.initState();
    //初始化聊天
    init();
    //初始化shareSdk
    initShare();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: AppConf.AppTitle,
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primaryColor: Colors.white),
//      home: Splash(),
      initialRoute: SplashPath,
      routes: Router.initRouters(),
    );
  }

  ///测试化测试，这里传自己应用的appid
  Future<void> init() async {
    await initHistory();
    var token = await getToken();

    try {
      if (_messageStreamSubscription == null) {
        _messageStreamSubscription = dim.onMessage.listen((dynamic onData) {
          print(
              "我监听到数据了$onData,需要在这里判断是你是消息列表还是需要刷新会话的请求。会话的请求是一个空的列表[],消息列表是有内容的");
          List _l = json.decode(onData);
          if (_l.length == 0) {
            ///代表此消息是会话消息，在会话消息页面注册消息监听
          } else {
            if (Platform.isIOS) {
              ///代表此消息是接受到的消息，在消息页面注册消息监听
              for (int i = 0; i < _l.length; i++) {
                ///解析timConversation,查看会话消息的type是否为1，或者3，为1就发送事件
                // Map<String, dynamic> _timConversation = _l[i]['timeConversation'];
                // print(_l[i]['timConversation']['type']);
                // print(_l[i]['timConversation']['type']==3);
                if (_l[i]['timConversation']['type'] == 3) {
                  ///表示未读的消息？？？待确
                }

                ///TODO 未确定其他类型的消息格式是什么样的
                else if (_l[i]['timConversation']['type'] == 1) {
                  // Map<String, dynamic> _msg = json.decode(_l[i]['message']);
                  print("转发消息");
                  print(ImMessage + _l[i]['sender']);
                  eventBus.emit(
                      ImMessage + _l[i]['sender'], _l[i]['message']['text']);
                }
              }
            }else {
              ///代表此消息是接受到的消息，在消息页面注册消息监听
              for (int i = 0; i < _l.length; i++) {
                ///解析timConversation,查看会话消息的type是否为1，或者3，为1就发送事件
                // Map<String, dynamic> _timConversation = _l[i]['timeConversation'];
                // print(_l[i]['timConversation']['type']);
                // print(_l[i]['timConversation']['type']==3);
                if (_l[i]['timConversation']['type'] == 3) {
                  ///表示未读的消息？？？待确
                }

                ///TODO 未确定其他类型的消息格式是什么样的
                else if (_l[i]['timConversation']['type'] == 'C2C') {
                  // Map<String, dynamic> _msg = json.decode(_l[i]['message']);
                  print("转发消息");
                  print(ImMessage + _l[i]['sender']);
                  eventBus.emit(
                      ImMessage + _l[i]['sender'], _l[i]['message']['text']);
                }
              }
            }
            // print(onData);
            // eventBus.emit(eventName,onData);
          }
        });
      }
      var result = await dim.init(DimAppId);
      if (token != null) {
        ///登录聊天系统
        // imUserSelf = ImUser(nick:"yyang",sig:"eJxlz8Fqg0AQgOG7TyFeLWVdsxoDPUSTJtoWMSbQ5iKLTmRdujHrGmNK373UBCp0rt8-DPOl6bpubF-TR5rnx1aoTPU1GPpMN5Dx8Id1zYqMqsyWxT*ES80kZPSgQA5oEUIwQuOGFSAUO7B70fdUlCNuCp4NN277E4QwRlNsjRNWDvi23AVhsnghZtruJRXzahV1vI1wZbqWaPv9yT5BXmyTxN-Q54p3XVj6HD7izdxslk64trvg6kT*JQbXe1*b7mJ6nqQxC2CV7zh-Gp1U7BPuDzmYuK7teSM9g2zYUQwBRhaxsI1*x9C*tR8sI10B");
        // await dimLogin("yyang",
        //     "eJxlz8Fqg0AQgOG7TyFeLWVdsxoDPUSTJtoWMSbQ5iKLTmRdujHrGmNK373UBCp0rt8-DPOl6bpubF-TR5rnx1aoTPU1GPpMN5Dx8Id1zYqMqsyWxT*ES80kZPSgQA5oEUIwQuOGFSAUO7B70fdUlCNuCp4NN277E4QwRlNsjRNWDvi23AVhsnghZtruJRXzahV1vI1wZbqWaPv9yT5BXmyTxN-Q54p3XVj6HD7izdxslk64trvg6kT*JQbXe1*b7mJ6nqQxC2CV7zh-Gp1U7BPuDzmYuK7teSM9g2zYUQwBRhaxsI1*x9C*tR8sI10B");
        imUserSelf = await getIm();
        await dimLogin(imUserSelf.nick, imUserSelf.sig);
      }
      print(result);
      // setState(() {
      //   this._result = result;
      // });
    } on PlatformException {
      print("初始化失败");
    }
  }

  initShare() {
    // ShareSDKRegister register = ShareSDKRegister();

    // register.setupWechat(
    //     "wx617c77c82218ea2c", "c7253e5289986cf4c4c74d1ccc185fb1");
    // register.setupSinaWeibo("568898243", "38a4f8204cc784f81f9f0daaf31e02e3",
    //     "http://www.sharesdk.cn");
    // register.setupQQ("100371282", "aed9b0303e3ed1e27bae87c33761161d");
    // register.setupFacebook(
    //     "1412473428822331", "a42f4f3f867dc947b9ed6020c2e93558", "shareSDK");
    // register.setupTwitter("viOnkeLpHBKs6KXV7MPpeGyzE",
    //     "NJEglQUy2rqZ9Io9FcAU9p17omFqbORknUpRrCDOK46aAbIiey", "http://mob.com");
    // ShareSDK.regist(register);

    // ShareSDK.listenNativeEvent();
  }
}

class ImUser {
  final String nick;
  final String sig;
  ImUser({@required this.nick, @required this.sig});
}
